"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFileAsync = exports.getFileCB = void 0;
const http = require("http");
const fs = require("fs");
function getFileCB(url, targetPath, cb) {
    http.get(url, (res) => {
        //HTTP状态码
        const { statusCode } = res;
        if (statusCode !== 200) {
            let error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`);
            console.error(`getFile HttpConnection error: ${error.message}`);
            res.resume();
            cb(error);
            return;
        }
        //文件写入流
        let ws = fs.createWriteStream(targetPath);
        ws.on('error', (e) => {
            console.error(`getFile WriteStream error: ${e.message}`);
            cb(e);
        });
        //返回流
        res.pipe(ws);
        res.on('error', (e) => {
            console.error(`getFile ResponseStream error: ${e.message}`);
            cb(e);
        });
        //正常结束
        res.on('end', () => {
            cb();
        });
    }).on('error', (e) => {
        //异常中断
        console.error(`getFile HttpConnection error: ${e.message}`);
        cb(e);
    });
}
exports.getFileCB = getFileCB;
async function getFileAsync(url, targetPath) {
    return new Promise((resolve, reject) => {
        getFileCB(url, targetPath, (e) => {
            if (e)
                reject(e);
            else
                resolve();
        });
    });
}
exports.getFileAsync = getFileAsync;
